package cn.wolfcode.web.util;

import cn.wolfcode.web.domain.Employee;
import cn.wolfcode.web.mapper.PermissionMapper;
import cn.wolfcode.web.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component("crmRealm")//创建CRMReaml对象
public class CRMReaml extends AuthorizingRealm {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    //获取认证信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo();
        //获取到当前登录的用户
        Employee employee = (Employee) principals.getPrimaryPrincipal();
        //如果是超级管理员，授予其admin的角色和所有权限
        if (employee.isAdmin()) {
            info.addRole("admin");
            info.addStringPermission("*:*");
        } else {
            //根据登录用户的id查询到其拥有的所有角色的编码
            List<String> roleSns = roleMapper.selectRoleSnsByEmpId(employee.getId());//
//            根据登录用户的id查询到其拥有的所有权限表达式
            List<String> expressions = permissionMapper.selectExpressionsByEmpId(employee.getId());

            //将用户拥有的角色和权限添加到授权信息对象中，供Shiro权限校验时使用
            info.addRoles(roleSns);
            info.addStringPermissions(expressions);
        }


     /*   List<String> roles = new ArrayList<>();
        roles.add("role1");
        roles.add("role2");
        List<String> permissions = new ArrayList<>();
        permissions.add("user:list");
        permissions.add("user:delete");
        permissions.add("user:update");
        info.addRoles(roles);
        info.addStringPermissions(permissions);*/
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//       模拟数据库的真实账号和密码
        String username = "zhangsan";
        String password = "555";
//        如果账号正确,返回一个AuthenticationInfo对象
//    token 是装密码和账号信息的身份凭证
        if (username.equals(token.getPrincipal())) {
            return new SimpleAuthenticationInfo(username,
                    password,
                    this.getName());//数据源:当前 Realm 的名称
        }
        return null;
    }
}
